package com.hngy.xpq.fileiodemo.tool;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class FileStorage {

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    /**
     * 写入SD卡
     * @param activity
     * @param fileName
     * @param text
     */
    public static void saveSDFile(Activity activity, String fileName, String text) {
        // 判断SD卡是否有读写权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File p = Environment.getExternalStorageDirectory();
            String strPath = p.getAbsolutePath();
            File q = new File(strPath + "/xpq/" + fileName + ".txt");
            try {
                FileOutputStream out = new FileOutputStream(q);
                out.write(text.getBytes());
                out.flush();
                out.close();
                Toast.makeText(activity, "SD文件保存成功!", Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.i("file", "文件未找到!");
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("file", "其他异常!");
            }
        } else {
            // 没有 就再次提醒
            verifyStoragePermissions(activity);
            Log.i("file", "sd卡不可访问!");
        }
    }

    /**
     * 读取SD卡
     * @param activity
     * @param fileName
     */
    public static String readSDFile(Activity activity, String fileName) {
        String x = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File p = Environment.getExternalStorageDirectory();
            String strPath = p.getAbsolutePath();
            File q = new File(strPath + "/xpq/", fileName + ".txt");
            try {
                FileInputStream put = new FileInputStream(q);
                byte[] buffer = new byte[1024];
                int bytes = put.read(buffer);
                x = new String(buffer, 0, bytes);
            } catch (FileNotFoundException e) {
                x = "文件不存在!";
            } catch (IOException e) {
                x = "IO流错误!";
            }
        } else {
            verifyStoragePermissions(activity);
        }
        return x;
    }

    /**
     * 写入内部存储器
     * @param activity
     * @param fileName
     * @param text
     */
    public static void saveFile(Activity activity, String fileName, String text) {
        try {
            FileOutputStream out = activity.openFileOutput(fileName + ".txt", activity.MODE_PRIVATE);
            out.write(text.getBytes());
            out.flush();
            out.close();
            Toast.makeText(activity, "内部文件保存成功!", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取内部存储器
     * @param activity
     * @param fileName
     * @return
     */
    public static String readFile(Activity activity, String fileName) {
        String x = "";
        byte[] buffer = new byte[1024];
        FileInputStream in = null;
        try {
            in = activity.openFileInput(fileName + ".txt");
            int bytes = in.read(buffer);
            x = new String(buffer, 0, bytes);
        } catch (FileNotFoundException e) {
            x = "文件不存在!";
        } catch (IOException e) {
            x = "IO流错误!";
        }
        return x;
    }

    /**
     * 获取权限
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // 当前是否有写入的权限
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，提醒授权
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    1);
        }
    }

    /**
     * 遍历文件夹
     * @param activity
     */
    public static void listFiles(Activity activity) {
        String[] strings = activity.fileList();
        for (int i = 0; i < strings.length; i++) {
            Log.i("strings", strings[i]);
        }
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            File p = Environment.getExternalStorageDirectory();
//            File file = new File(p.getAbsolutePath() + "/xpq");
//            File[] listFile = file.listFiles();
//            for (int i = 0; i < listFile.length; i++) {
//                Log.i("listFiles", listFile[i].getName());
//            }
//        } else {
//            verifyStoragePermissions(activity);
//        }
    }

    /**
     * 创建初始文件夹
     **/
    public static void createFile() {
        File p = Environment.getExternalStorageDirectory();
        //生成用户存储文件的地址
        String userPath = p.getAbsolutePath() + "/xpq";
        File file=new File(userPath);
        //如果文件夹不存在
        if(!file.exists()){
            //创建文件夹
            file.mkdir();
        }
    }

}
